package com.vincce.sport.interceptor;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.vincce.sport.core.utils.Constant;
import com.vincce.sport.core.utils.SimpleStorageClient;
import com.vincce.sport.core.weixin.WeixinTask;
import com.vincce.sport.entity.Advert;
import com.vincce.sport.entity.Bottom;
import com.vincce.sport.entity.Page;
import com.vincce.sport.entity.User;
import com.vincce.sport.mapper.AdvertMapper;
import com.vincce.sport.mapper.BottomMapper;
import com.vincce.sport.mapper.UserMapper;

public final class AuthenticateInterceptor extends HandlerInterceptorAdapter {
    private static final Logger LOGGER = Logger.getLogger(AuthenticateInterceptor.class);
    @Resource
	private AdvertMapper advertMapper;
    @Resource
	private UserMapper userMapper;
	@Resource
	private BottomMapper footerMapper;
    /*private String mappingURL;//利用正则映射到需要拦截的路径
    
    public void setMappingURL(String mappingURL) {    
           this.mappingURL = mappingURL;    
   } */
    
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
    	Map<String, Object> filter = new HashMap<String, Object>();
    	Page<Advert> headAdvertPage=new Page<Advert>();
		//首页头部广告位
		filter.put("name", "首页头部");
	    filter.put("status", 1);
	    headAdvertPage.setLimit(1);
	    headAdvertPage.setFilter(filter);
	    headAdvertPage.setResult(replace(advertMapper.queryAdvertList(headAdvertPage)));
	    request.getSession().setAttribute(Constant.T_INDEX_ADVERT, headAdvertPage); 
	    //判断论坛用户是否存在
	    User user=(User)request.getSession().getAttribute(Constant.T_USER);
	    if(user!=null && user.getType()!=null){
	    	if(user.getType().equals("1")){
	    		User userInfo=new User();
		    	userInfo.setUserName(user.getUserName());
		    	List<User> userList = userMapper.findUserByOne(userInfo);
		        if(userList!=null && userList.size()>0){
			    	//存在此用户
		        }else{
		        	//不存在，则添加
	                user.setCreateUser(null);
	                user.setCreateTime(new Date());
	                user.setUpdateTime(new Date());
	                user.setStatus(1);
	                userMapper.insertUser(user);
	                System.out.println("------------------注册成功---------------------");
		        }
	    	}
	    }
	    //获取粉丝数
	    String jsonData = sendGet("http://v.t.sina.com.cn/widget/widget_blog.php?uid=5225858022");
	    String fansNum = "0";
	    if(jsonData.indexOf("粉丝") != -1 && jsonData.indexOf("人") != -1){
	    	fansNum = jsonData.substring(jsonData.indexOf("粉丝")+2,jsonData.indexOf("人"));
	    }
	    //页面底部
	    List<Bottom> footerList= footerMapper.queryBottomByParentId(0);
		if(footerList!=null && footerList.size()>0){
			for(int i=0;i<footerList.size();i++){
				Integer p=footerList.get(i).getId();
				footerList.get(i).setFooterList(replaceFooter(footerMapper.queryBottomByParentId(p)));				
			}
		}else{
			footerList=new ArrayList<Bottom>();
		}
		String footer=getFooterStr(footerList);
	    request.getSession().setAttribute(Constant.T_INDEX_FANS, fansNum); 
	    request.getSession().setAttribute(Constant.T_INDEX_WEIXIN, WeixinTask.TOTAL_ATTENTION);
	    request.getSession().setAttribute(Constant.T_INDEX_FOOTER, footer);
    	System.out.println("------------------interceptor---------------------");
		return true;
    }
    /**
	 * 图片路径替换
	 * @param imgStorageList
	 * @return
	 */
	public List<Advert> replace(List<Advert> advertList){
		if(advertList!=null && advertList.size()>0){
			for(Advert adv:advertList){
				adv.setAdvertImg(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+adv.getAdvertImg(), "ori"));
			}
		}
		return advertList;
	}
	
	public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            connection.setConnectTimeout(60000);
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            /*// 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }*/
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }
	/**
	 * 图片路径替换
	 * @param imgStorageList
	 * @return
	 */
	public List<Bottom> replaceFooter(List<Bottom> imgStorageList){
		if(imgStorageList!=null && imgStorageList.size()>0){
			for(Bottom isl:imgStorageList){
				isl.setImgUrl(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+isl.getImgUrl(), "ori"));
			}
		}
		return imgStorageList;
	}
	
	public String getFooterStr(List<Bottom> footerList){
		String footer="";
		if(footerList!=null && footerList.size()>0){
			for(int i=0;i<footerList.size();i++){
				String rName="";
				String name=footerList.get(i).getName();
				if(name.indexOf("&")>-1){
					rName=name.replaceAll("&", "&#38;");
				}else{
					rName=name;
				}
				if(i==4 || i==5){
					footer+="<div class='code-block'>";
					footer+="	<div class='d2doc'>"+rName+"</div>";
					if(footerList.get(i).getFooterList()!=null && footerList.get(i).getFooterList().size()>0){
						footer+="	<div class='d2cod'><img src='"+footerList.get(i).getFooterList().get(0).getImgUrl()+"'/></div>";
					}					
					footer+="</div>";
				}else{
					footer+="<div class='footer-block'>";
					footer+="	<dl>";
					footer+="		<dt>"+rName+"</dt>";
					if(footerList.get(i).getFooterList()!=null){
						for(int j=0;j<footerList.get(i).getFooterList().size();j++){
							String rHref="";
							String href=footerList.get(i).getFooterList().get(j).getFooterHref();
							if(href.indexOf("&")>-1){
								rHref=href.replaceAll("&", "&#38;");
							}else{
								rHref=href;
							}
							String rName1="";
							String name1=footerList.get(i).getFooterList().get(j).getName();
							if(name1.indexOf("&")>-1){
								rName1=name1.replaceAll("&", "&#38;");
							}else{
								rName1=name1;
							}
							footer+="		<dd><a target='_blank' href='"+rHref+"'>"+rName1+"</a></dd>";
						}
					}					
					footer+="	</dl>";
					footer+="</div>";
				}
			}
		}		
		return footer;
	}
}
